<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属地点" prop="locationId">
        <el-select
          v-model="queryParams.locationId"
          placeholder="请选择所属地点"
          clearable
          filterable
        >
          <el-option v-for="location in locationList" :key="location.locationId" :label="location.locationName" :value="location.locationId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable>
          <el-option label="正常" value="0"></el-option>
          <el-option label="故障" value="1"></el-option>
          <el-option label="维修中" value="2"></el-option>
          <el-option label="离线" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="安装时间" prop="installTime">
        <el-date-picker clearable
          v-model="queryParams.installTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择安装时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 权限提示卡片 -->
    <el-alert
      v-if="!isAdmin && Object.keys(accessibleLocations).length === 0"
      title="您当前没有任何监控设备的访问权限"
      type="warning"
      description="请先提交申请并获得批准，才能查看相应地点的监控设备"
      show-icon
      :closable="false"
      style="margin-bottom: 15px;"
    >
      <template slot="title">
        您当前没有任何监控设备的访问权限
        <el-button size="mini" type="primary" @click="goToRequestPage" style="margin-left: 15px;">
          申请访问权限
        </el-button>
      </template>
    </el-alert>
    
    <!-- 过期权限提示卡片 -->
    <el-alert
      v-if="!isAdmin && hasExpiredLocations"
      title="您有部分地点的访问权限已过期"
      type="info"
      description="请重新申请访问权限以继续查看这些地点的监控设备"
      show-icon
      style="margin-bottom: 15px;"
    >
      <template slot="title">
        您有部分地点的访问权限已过期
        <el-button size="mini" type="primary" @click="goToRequestPage" style="margin-left: 15px;">
          重新申请
        </el-button>
      </template>
    </el-alert>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['monitor:device:add']"
        >新增设备</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['monitor:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['monitor:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['monitor:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="deviceId" width="100" />
      <el-table-column label="设备名称" align="center" prop="deviceName" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="所属地点" align="center" prop="locationName" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="设备状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 0">正常</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status == 1">故障</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status == 2">维修中</el-tag>
          <el-tag type="info" v-else-if="scope.row.status == 3">离线</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="安装时间" align="center" prop="installTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.installTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" align="center" prop="ipAddress" min-width="120" />
      <el-table-column label="RTSP端口" align="center" prop="port" width="100" />
      <el-table-column label="通信协议" align="center" prop="protocol" width="100" />
      <el-table-column label="访问权限" align="center" width="100">
        <template slot-scope="scope">
          <el-tag type="success" v-if="isAdmin || checkDeviceAccessible(scope.row)">可访问</el-tag>
          <el-tag type="danger" v-else>无权限</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['monitor:device:edit']"
            :disabled="!isAdmin && !checkDeviceAccessible(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['monitor:device:remove']"
            :disabled="!isAdmin && !checkDeviceAccessible(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            :disabled="!isAdmin && !checkDeviceAccessible(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="handleMonitor(scope.row)"
            v-hasPermi="['monitor:device:query']"
            :disabled="!isAdmin && !checkDeviceAccessible(scope.row)"
          >查看监控</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监控设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="所属地点" prop="locationId">
          <el-select
            v-model="form.locationId"
            placeholder="请选择所属地点"
            filterable
          >
            <el-option v-for="location in locationList" :key="location.locationId" :label="location.locationName" :value="location.locationId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择设备状态">
            <el-option label="正常" value="0"></el-option>
            <el-option label="故障" value="1"></el-option>
            <el-option label="维修中" value="2"></el-option>
            <el-option label="离线" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装时间" prop="installTime">
          <el-date-picker clearable
            v-model="form.installTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择安装时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址">
            <template slot="prepend">http://</template>
          </el-input>
        </el-form-item>
        <el-form-item label="RTSP默认端口" prop="port">
          <el-input-number v-model="form.port" :min="1" :max="65535" placeholder="请输入RTSP默认端口" />
        </el-form-item>
        <el-form-item label="通信协议" prop="protocol">
          <el-select v-model="form.protocol" placeholder="请选择通信协议">
            <el-option label="RTSP" value="RTSP"></el-option>
            <el-option label="RTMP" value="RTMP"></el-option>
            <el-option label="HLS" value="HLS"></el-option>
            <el-option label="HTTP" value="HTTP"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看监控设备详情对话框 -->
    <el-dialog title="设备详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备编号">{{ viewForm.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ viewForm.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="所属地点">{{ viewForm.locationName }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag type="success" v-if="viewForm.status == 0">正常</el-tag>
          <el-tag type="danger" v-if="viewForm.status == 1">故障</el-tag>
          <el-tag type="warning" v-if="viewForm.status == 2">维修中</el-tag>
          <el-tag type="info" v-if="viewForm.status == 3">离线</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="安装时间">{{ parseTime(viewForm.installTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ viewForm.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="RTSP端口">{{ viewForm.port }}</el-descriptions-item>
        <el-descriptions-item label="通信协议">{{ viewForm.protocol }}</el-descriptions-item>
        <el-descriptions-item label="设备RTSP链接" :span="2">
          rtsp://{{ viewForm.ipAddress }}:{{ viewForm.port }}/{{ viewForm.deviceName }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/newMonitor/device";
import { listLocation } from "@/api/newMonitor/location";
import { getUserAccessibleLocations } from "@/api/newMonitor/request";

export default {
  name: "Device",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控设备表格数据
      deviceList: [],
      // 完整设备列表（未经权限过滤）
      allDeviceList: [],
      // 地点列表
      locationList: [],
      // 可访问的地点ID列表
      accessibleLocations: {},
      // 是否为管理员
      isAdmin: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        locationId: null,
        status: null,
        installTime: null,
      },
      // 表单参数
      form: {},
      // 详情表单
      viewForm: {},
      // 表单校验
      rules: {
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        locationId: [
          { required: true, message: "所属地点不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "设备状态不能为空", trigger: "change" }
        ],
        ipAddress: [
          { required: true, message: "IP地址不能为空", trigger: "blur" },
          { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: "IP地址格式不正确", trigger: "blur" }
        ],
        port: [
          { required: true, message: "RTSP端口不能为空", trigger: "blur" }
        ],
        protocol: [
          { required: true, message: "通信协议不能为空", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    // 检查是否有过期的地点权限
    hasExpiredLocations() {
      if (this.isAdmin) {
        return false;
      }
      
      // 查找值为false的地点（表示已过期）
      for (const locationId in this.accessibleLocations) {
        if (this.accessibleLocations[locationId] === false) {
          return true;
        }
      }
      
      return false;
    }
  },
  created() {
    // 判断当前用户是否为管理员
    const roles = this.$store.getters.roles;
    this.isAdmin = roles.includes('admin');
    
    // 获取可访问地点列表
    this.getAccessibleLocations().then(() => {
      // 获取设备列表
      this.getList();
      // 获取地点列表
      this.getLocationList();
    });
  },
  methods: {
    /** 跳转到申请页面 */
    goToRequestPage() {
      this.$router.push('/monitor/request/request');
    },
    
    /** 获取用户可访问的地点列表 */
    async getAccessibleLocations() {
      try {
        if (this.isAdmin) {
          // 管理员无限制
          this.accessibleLocations = {};
          return Promise.resolve();
        }
        
        const response = await getUserAccessibleLocations();
        this.accessibleLocations = response.data || {};
        console.log('获取到的可访问地点列表:', this.accessibleLocations);
      } catch (error) {
        console.error('获取可访问地点列表失败:', error);
        this.$message.warning('权限获取失败，您可能无法访问某些设备，请联系管理员');
        // 出错时使用空对象
        this.accessibleLocations = {};
      }
      return Promise.resolve();
    },
    
    /** 检查设备是否可访问 */
    checkDeviceAccessible(device) {
      // 管理员可以访问所有设备
      if (this.isAdmin) {
        return true;
      }
      
      // 没有地点信息的设备不可访问
      if (!device.locationId) {
        return false;
      }
      
      // 检查设备所在地点是否在可访问列表中且未过期
      const locationId = device.locationId;
      return this.accessibleLocations.hasOwnProperty(locationId) && this.accessibleLocations[locationId] !== false;
    },
    
    /** 查询监控设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        // 处理数据，将ID转换为名称
        const rows = response.rows || [];
        rows.forEach(row => {
          // 设置地点名称
          const location = this.locationList.find(l => l.locationId == row.locationId);
          row.locationName = location ? location.locationName : row.locationId;
        });
        
        // 保存完整列表
        this.allDeviceList = [...rows];
        
        // 根据权限过滤设备
        this.filterDevicesByPermission();
        
        this.total = this.deviceList.length;
        this.loading = false;
      });
    },
    
    /** 根据权限过滤设备列表 */
    filterDevicesByPermission() {
      // 如果是管理员，显示所有设备但标记权限
      if (this.isAdmin) {
        this.deviceList = [...this.allDeviceList];
        return;
      }
      
      // 普通用户仍显示所有设备，但在操作时进行权限控制
      this.deviceList = [...this.allDeviceList];
      
      // 如果过滤后没有可操作的设备，提示用户
      const hasAccessibleDevices = this.deviceList.some(device => this.checkDeviceAccessible(device));
      if (!hasAccessibleDevices && this.deviceList.length > 0) {
        this.$message.warning('您没有任何设备的访问权限，请先申请访问权限');
      }
    },
    
    // 获取地点列表
    getLocationList() {
      listLocation().then(response => {
        this.locationList = response.rows || [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceName: null,
        locationId: null,
        status: "0", // 默认为正常状态
        installTime: null,
        ipAddress: null,
        port: 554, // 默认RTSP端口
        protocol: "RTSP" // 默认RTSP协议
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监控设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 检查是否有权限修改
      if (!this.isAdmin && !this.checkDeviceAccessible(row)) {
        this.$message.error('您没有权限修改此设备，请先申请相应地点的访问权限');
        return;
      }
      
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改监控设备";
      });
    },
    /** 查看详情 */
    handleView(row) {
      // 检查是否有权限查看
      if (!this.isAdmin && !this.checkDeviceAccessible(row)) {
        this.$message.error('您没有权限查看此设备详情，请先申请相应地点的访问权限');
        return;
      }
      
      this.viewForm = { ...row };
      this.viewOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 检查是否有权限删除
      if (!this.isAdmin && !this.checkDeviceAccessible(row)) {
        this.$message.error('您没有权限删除此设备，请先申请相应地点的访问权限');
        return;
      }
      
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除监控设备编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('monitor/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    /** 跳转到实时监控页面 */
    handleMonitor(row) {
      // 检查是否有权限查看监控
      if (!this.isAdmin && !this.checkDeviceAccessible(row)) {
        this.$message.error('您没有权限查看此设备的监控，请先申请相应地点的访问权限');
        return;
      }
      
      const deviceId = row.deviceId;
      this.$router.push({
        path: `/newMonitor/monitor-view/index/${deviceId}`,
        query: {
          deviceName: row.deviceName
        }
      });
    }
  }
};
</script>

<style scoped>
.el-tag {
  margin-right: 5px;
}

.mb8 {
  margin-bottom: 12px;
}

/* 禁用状态的表格按钮 */
.el-table .el-button.is-disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>
